<template>
  <div style="width: 100%;height:100%">
    <a-form-model
    ref="formComp"
    :model="formData"
    layout="horizontal"
    class="AsteriskAfter newEditStyle h100 editConditionStrategyFormComp rightDrawerWithoutCol">
    <EditStrategy :showPolicyName="false" ref="strategyRef"></EditStrategy>
    <a-form-model-item :label="$t('yuyueshengjie')" class="customFormModelItem" style="margin-top:20px">
    </a-form-model-item>
    <a-form-model-item>
      <div class="editTestFormBoxTableList">
        <a-table  :dataSource="appointTimeDataSource" :columns="appointTimeColumns" :pagination="false">
          <template slot="appointTime" slot-scope="text,record">
            <a-range-picker v-if="currentRecord.id==record.id"
                            :placeholder="[$t('startTime'), $t('endTime')]"
                            :showTime="{ format: 'HH:mm:ss' }"
                            format="YYYY-MM-DD HH:mm:ss"
                            @change="onTimeRangeChange"
                            :value="defaultTimeRange"
                            :disabled-date="disabledDate"
                            :disabledTime="disabledEndTime"
                            :allow-clear="false"
                            style="max-width:100%"
                            :inputReadOnly="true"
                            @ok="handleConfirm(record.id)"
            />
            <template v-else>
              {{record.startTime}} ~ {{record.endTime}}
            </template>
          </template>
          <template slot="operation" slot-scope="text,scope,index">
            <!-- <el-button type="text" v-if="currentRecord.id==scope.id" @click="handleConfirm(scope.id)">{{$t('确定')}}</el-button> -->
            <el-button type="text" @click="handleEdit(scope.id)">{{$t('edit')}}</el-button>
            <el-button type="text" v-if="upgradeTriggerType == '2'" @click="handleDelete(scope)">{{$t('delete')}}</el-button>
            <el-button type="text" v-if="index == (appointTimeDataSource.length-1) && upgradeTriggerType == '2'" @click="handleAdd(scope)">{{$t('add')}}</el-button>
          </template>
        </a-table>
      </div>
    </a-form-model-item>

    <a-radio-group style="padding-bottom: 24px;margin-top:20px" name="radioGroup" v-model="dataSource[dataAdress].choseType">
      <a-radio :value="1">
        {{ $t('fileImport') }}
      </a-radio>
    </a-radio-group>
    <div>
      <a-input
        class="formFileInput"
        :placeholder="$t('formatFiles')"
        readOnly
        :value="dataSource[dataAdress].file.name"
      >
        <template #addonAfter>
          <i class="iconfont icon-shangchuan" @click="upload"></i>
        </template>
      </a-input>
      <!-- 下载模板 -->
      <a-button
        @click="downloadFile"
        :loading="downloading"
        style="vertical-align: text-bottom;"
      >{{ $t('downloadTemplate') }}
      </a-button>
      <div v-if="uploadRes.total!=0">
        <p style="line-height:30px">
          <span>文件车辆数：{{ uploadRes.total||'-' }}</span>
          <span style="margin-left:20px">导入车辆数：</span><span style="color: green">{{ uploadRes.success ||'-' }}</span>
          <span style="margin-left:20px">失败车辆数：</span><span style="color: red">{{ uploadRes.fail||'-' }}</span>
        </p>
        <p style="line-height:60px">
          <a-button @click="downloadImportResultFile" v-if="uploadRes.detailExcelUrl">{{$t("exportResult")}}</a-button>
        </p>
      </div>
      <div v-if="uploadRes.total==0">
        <a-empty style="margin-top:77px">
          <span slot="description">导入车辆文件内容为空!</span>
        </a-empty>
      </div>
      <!-- 来自文件上传 -->
      <local-upload
        ref="upload"
        :domView="false"
        @showFileObj="showFileObj"
        :accept="['.xls','.xlsx']"
      ></local-upload>
    </div>
  </a-form-model>

  
  </div>
</template>
<script>
import moment from 'moment'
import EditStrategy from '@/views/strategy/FotaCondition/components/EditStrategy.vue'
import LocalUpload from '@/components/Upload/LocalUpload'
import { downloadBlobFile } from '@/utils/functions'
import { mapState } from 'vuex'
export default {
  components: {
    EditStrategy,
    LocalUpload
  },
  props:{
    upgradeTriggerType: {
      type: Number,
      default: 1
    },
    dataAdress: {
      type: String,
      default: 'detailAddCar'
    },
    auditInfo:{
      type:Object,
      default:{}
    },
    strategyId: {
      type: String,
      default: ''
    },
    taskId: {
      type: String,
      default: ''
    },
  },
  data () {
    return {
      uploadRes: {
        fail: null,
        success: null,
        total: null
      },
      downloading: false,
      isReadonly:false,
      formData:{
        // 有效期开始时间
        startTime: '',
        // 有效期结束时间
        endTime: '',
      },
      currentRecord:{},
      appointTimeColumns:[
        {
          title: '预约升级时间',
          dataIndex: 'appointTime',
          key: 'appointTime',
          scopedSlots: { customRender: 'appointTime' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      //默认一行数据
      appointTimeDataSource:[
        {
          id:new Date().getTime(),
          startTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(new Date().getTime()).add(this.upgradeTriggerType === 'USER' ? 43200 : 30, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      ]
    }
  },
  created () {},
  mounted () {},
  destroyed(){
    // this.$store.commit('RESET_NEWTASK_DATA')
    this.$store.commit('RESET_ADDCAR')
  },
  computed: {
    // 有效期选择的默认值
    defaultTimeRange () {
      if (this.formData.startTime && this.formData.endTime) {
        return [moment(this.formData.startTime), moment(this.formData.endTime)]
      }
      return []
    },
    ...mapState({
      dataSource: (state) => state.newTask
    })
  },
  methods: {
    // 获取表单中的数据
    getFormData () {
      return new Promise((resolve, reject) => {
        if(!this.$refs.strategyRef.toQualityFormData().items.length){
          reject()
          return 
        }
        else if(!this.dataSource[this.dataAdress].pretreatmentId){
          this.$message.warning('未导入车辆！')
          reject()
          return 
        }
        if(this.handleConfirm()==false){
          return
        }
        else{
          const data = {
            auditInfo:this.auditInfo,
            status:'PASS',
            items:this.$refs.strategyRef.toQualityFormData().items,
            taskVehicleAppointTimeDtoList:this.appointTimeDataSource,
            pretreatmentId:this.dataSource[this.dataAdress].pretreatmentId
          }
          console.log('#@@#$@',data)
          resolve(data)
        }
      })
    },
    handleEdit(id){
      this.currentRecord = this.appointTimeDataSource.filter(item => id === item.id)[0]
      this.formData.startTime = this.currentRecord.startTime
      this.formData.endTime = this.currentRecord.endTime
    },
    handleConfirm(id){
      //TODO 判断时间是否有重合
      const appointTimeDataSourceCopy=[...this.appointTimeDataSource]
      appointTimeDataSourceCopy.sort((a,b)=>{
        return new Date(a.startTime)-new Date(b.startTime)
      })
      for(let i=0;i<appointTimeDataSourceCopy.length;i++){
        if(i>0){
          if(moment(appointTimeDataSourceCopy[i].startTime).isBefore(moment(appointTimeDataSourceCopy[i-1].endTime))){
            this.$message.error("与现有时间段重合！")
            return false
          }
        }
      }
      this.currentRecord ={}
    },
    handleAdd(scope){
      this.appointTimeDataSource.push(
        {
          id:new Date().getTime(),
          startTime:moment(scope.endTime).add(1, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(scope.endTime).add(31, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      )
    },
    handleDelete(record){
      if (this.appointTimeDataSource.length === 1) {
        this.$message.error("默认要有一行数据！")
        return
      }
      this.appointTimeDataSource = this.appointTimeDataSource.filter(item => record.id !== item.id)
    },
    onTimeRangeChange (date, dateString) {
      if (date.length === 0) {
        this.formData.startTime = ''
        this.formData.endTime = ''
        return false
      }
      const minDays = 1
      //if (moment(date[1]).diff(moment(date[0]), 'days') < minDays) {
      //  this.$message.error(this.$t('newTaskTimeTip2'))
        // eslint-disable-next-line prefer-destructuring
        //this.formData.startTime = dateString[0]
        //this.formData.endTime = moment(dateString[0]).add(minDays, 'days').format('YYYY-MM-DD HH:mm:ss')
      //  return false
      //}
      // eslint-disable-next-line prefer-destructuring
      this.formData.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.formData.endTime = dateString[1]
      //更新日期到时间数组中
      this.appointTimeDataSource.forEach(data=>{
        if (data.id == this.currentRecord.id){
          data.startTime= dateString[0]
          data.endTime= dateString[1]
        }

      })

    },
    disabledDate (current) {
      return current < moment().subtract(1,"days").endOf('day')
    },
    range(start, end){
      const result = [];
      for (let i = start; i < end; i++) {
          result.push(i);
      }
      return result;
    },
    disabledEndTime(date,type){
      let currentDay = moment().date();    //当下的时间
      let currentHours = moment().hours();
      let currentMinutes = moment().minutes(); 
      if(type=='start' && date){
        let settingHours = moment(date[0]).hours();
        let settingDay = moment(date[0]).date();
        if (date[0] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[0] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
                disabledMinutes: () => [],
            };   
        }else if (date[0] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[0] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }else if(type=='end' && date){ 
        let settingHours = moment(date[1]).hours();
        let settingDay = moment(date[1]).date();
        if (date[1] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[1] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间
                disabledMinutes: () => [],
            };   
        }else if (date[1] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[1] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }
    },
    //   上传文件
    upload () {
      this.$refs.upload.uploadDo()
    },
    // 回显上传文件
    showFileObj (value) {
      const vm = this
      vm.dataSource[vm.dataAdress].file = value
      const formData = new FormData()
      formData.append('file', value)
      formData.append('strategyId', this.strategyId)
      formData.append('taskId',this.taskId)
      
      vm.dataSource[vm.dataAdress].pretreatmentId = null
      vm.$api.fliePretreatment(formData).then(res => {
        if (res.data && res.data.pretreatmentId) {
          vm.dataSource[vm.dataAdress].pretreatmentId = res.data.pretreatmentId
          vm.dataSource[vm.dataAdress].fileFailCar = res.data.failNumber + res.data.repeatNumber
          vm.dataSource[vm.dataAdress].fileSuccessCar = res.data.successNumber
          vm.dataSource[vm.dataAdress].fileTotal = res.data.failNumber + res.data.repeatNumber + res.data.successNumber

          this.uploadRes = Object.assign(this.uploadRes, res.data);
          this.uploadRes.fail = res.data.failNumber + res.data.repeatNumber
          this.uploadRes.success = res.data.successNumber
          this.uploadRes.total = res.data.failNumber + res.data.repeatNumber + res.data.successNumber
        }
      }).catch(() => {
        vm.dataSource[vm.dataAdress].file = {}
      })
    },
    // 下载模板
    downloadFile () {
      this.$api.downloadTaskCarTpl().then((res) => {
        downloadBlobFile(res, `${this.$t('downloadTemplate')}.xlsx`)
      }).finally(() => {
        this.downloading = false
      })
    },
    downloadImportResultFile () {
      if (!this.uploadRes.detailExcelUrl) {
        return ;
      }
      if (this.uploadRes.detailExcelUrl.indexOf("http") === 0) {
        window.open(this.uploadRes.detailExcelUrl);
        return ;
      }
      return this.axios({
        url: this.uploadRes.detailExcelUrl,
        method: 'post',
        responseType: 'blob'
      }).then((res) => {
        downloadBlobFile(res, "下载结果.xlsx")
      });
    },
  }
}
</script>
<style lang="less" scoped>
.editConditionStrategyFormComp {
  overflow: auto;
  position: relative;
}
// 来自文件时，上传和按钮位置
.formFileInput {
  width: calc(100% - 120px);
  margin-bottom: 18px;

  & ~ .ant-btn {
    width: 108px;
    padding: 0;
    margin-left:10px;
  }
}
</style>
